package cn.xutongxue.gtms.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import cn.xutongxue.gtms.base.DeleteRequest;
import cn.xutongxue.gtms.base.Errors;
import cn.xutongxue.gtms.base.Result;
import cn.xutongxue.gtms.constant.UserConstant;
import cn.xutongxue.gtms.entity.User;
import cn.xutongxue.gtms.entity.dto.user.LoginUserRequest;
import cn.xutongxue.gtms.entity.dto.user.UserAddRequest;
import cn.xutongxue.gtms.entity.dto.user.UserQueryRequest;
import cn.xutongxue.gtms.entity.dto.user.UserUpdateRequest;
import cn.xutongxue.gtms.entity.vo.UserInfoVo;
import cn.xutongxue.gtms.entity.vo.UserVo;
import cn.xutongxue.gtms.exception.BusinessException;
import cn.xutongxue.gtms.exception.ThrowUtils;
import cn.xutongxue.gtms.service.impl.UserServiceImpl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 用户信息Controller
 * @author XuTongXue
 * @since 2022-12-12
 */

@Slf4j
@RestController
@RequestMapping("/user")
@Api(tags = "用户管理")
@CrossOrigin
public class UserController {

    @Resource
    private UserServiceImpl userService;

    /**
     * 用户登录
     * @param LoginUserRequest 用户登录表单
     * @return userInfoVo 用户信息视图
     */
    @PostMapping("/login")
    @ApiOperation(value = "用户登录")
    public Result login(@ApiParam(name = "登录表单") @RequestBody LoginUserRequest LoginUserRequest) {
        if (LoginUserRequest == null) {
            throw new BusinessException(Errors.PARAMS_ERROR);
        }
        String idNumber = LoginUserRequest.getIdNumber();
        String password = LoginUserRequest.getPassword();
        String role = LoginUserRequest.getRole();
        if (StringUtils.isAllBlank(idNumber, password, role)) {
            throw new BusinessException(Errors.PARAMS_ERROR);
        }
        UserInfoVo userInfoVo = userService.login(idNumber, password, role);
        return Result.success(userInfoVo);
    }


    /**
     * 退出登录
     */
    @PostMapping("/logout")
    @ApiOperation(value = "退出登录")
    public Result logout() {
        StpUtil.logout();
        return Result.success(true);
    }

    // crud region
    @PostMapping("/add")
    @ApiOperation(value = "添加用户")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public Result addUser(@ApiParam(name = "添加用户表单") @RequestBody UserAddRequest userAddRequest, HttpServletRequest request) {
        if (userAddRequest == null) {
            throw new BusinessException(Errors.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userAddRequest, user);
        user.setAvatar(UserConstant.DEFAULT_AVATAR);
        user.setPassword(UserConstant.DEFAULT_PASSWORD);
        User loginUser = (User) request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        user.setCreator(loginUser.getUsername());
        user.setUpdator(loginUser.getUsername());
        user.setIsDeleted(0);
        user.setState(0);
        boolean result = userService.save(user);
        ThrowUtils.throwIf(!result, Errors.OPERATION_ERROR);
        return Result.success(user.getId());
    }

    @PostMapping("/delete")
    @ApiOperation(value = "删除用户")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public Result deleteUser(@ApiParam(name = "删除用户ID") @RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(Errors.PARAMS_ERROR);
        }
        boolean result = userService.removeById(deleteRequest.getId());
        return Result.success(result);
    }

    @PostMapping("/update")
    @ApiOperation(value = "更新用户信息")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public Result updateUser(@ApiParam(name = "更新用户信息表单") @RequestBody UserUpdateRequest userUpdateRequest) {
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(Errors.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, Errors.OPERATION_ERROR);
        return Result.success(true);
    }

    @PostMapping("/list/page")
    @ApiOperation(value = "分页查询用户")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public Result listUserVoByPage(@ApiParam(name = "查询用户条件") @RequestBody UserQueryRequest userQueryRequest) {

        long size = userQueryRequest.getSize();
        // 限制单页数量
        ThrowUtils.throwIf(size > 100, Errors.PARAMS_ERROR);
        Page<UserVo> userVoPage = userService.listUserVoByPage(userQueryRequest);
        return Result.success(userVoPage);
    }

    @GetMapping("/getUserInfo")
    @ApiOperation(value = "获取用户信息")
    @SaCheckLogin
    public Result getUserInfo() {
        User user = userService.getById(StpUtil.getLoginIdAsLong());
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(user, userInfoVo);
        return Result.success(userInfoVo);
    }
    // crud endregion

}
